package com.cskaoyan.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.cskaoyan.bean.Keyword;
import com.cskaoyan.bean.sysmanage.KeywordExcel;
import com.cskaoyan.exception.MarketException;
import com.cskaoyan.service.KeyWordService;

import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;

public class KeywordExcelListener extends AnalysisEventListener<KeywordExcel> {
    public KeyWordService keyWordService;

    public KeywordExcelListener() {
    }

    public KeywordExcelListener(KeyWordService keyWordService) {
        this.keyWordService = keyWordService;
    }

    //一行行读取excel内容
    @SneakyThrows
    @Override
    public void invoke(KeywordExcel keywordExcel, AnalysisContext analysisContext) {
        if (keywordExcel == null) {
            throw new MarketException("添加失败,文件数据为空");
        }


        Keyword keyword = new Keyword();
        keyword.setKeyword(keywordExcel.getKeyword());
        String url = keywordExcel.getUrl();
        if (StringUtils.isEmpty(url)) {
            url = "";
        }
        keyword.setUrl(url);
        Boolean isHot = keywordExcel.getIsHot();
        Integer hot = 0;
        if (isHot) {
            hot = 1;
        }
        keyword.setIsHot(hot);
        Boolean isDefault = keywordExcel.getIsDefault();
        Integer defaultValue = 0;
        if (isDefault) {
            defaultValue = 1;
        }
        keyword.setIsDefault(defaultValue);
        keyword.setUpdateTime(new Date());
        boolean result = this.existKeyword(keyWordService, keywordExcel.getKeyword());
        if (result) {
            //存在重复，则更新数据
            keyWordService.updateKeywordByKeyword(keyword);

        } else {
            //未重复，进行添加
            keyword.setAddTime(new Date());
            keyWordService.addKeyword(keyword);
        }
    }

    @SneakyThrows
    private boolean existKeyword(KeyWordService keyWordService, String keyword) {
        //判断keyword是否重复
        int num = keyWordService.selectKeyword(keyword);
        return num > 0;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
